<script setup lang="ts">
import axios from '../axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, reactive, ref, watch } from 'vue';
import { router } from '../router';
import { RoleType, roleTypeToString, Template, User } from '../model';
import RoleTag from '../components/RoleTag.vue';
import { useWindowSize } from '@vueuse/core';

const PAGE_COUNT = 10;
const pageCount = ref(0)
const currentPage = ref(1)

const tableData = ref<User[]>([])

const loadData = async (page: number = 1) => {
    // 请求数据
    const res = await axios.get('/admin/user')
    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '加载用户数据失败',
        })
        return
    }

    // 计算分页显示的数据
    const allUsers: User[] = res.data['users']
    tableData.value = allUsers.slice((page - 1) * PAGE_COUNT, page * PAGE_COUNT)

    // 刷新分页数
    pageCount.value = Math.ceil(allUsers.length / PAGE_COUNT)
}

loadData()

const dialogMode = ref<'create' | 'edit'>()
const dialogVisible = ref(false)
const { width } = useWindowSize()
const dialogWidth = computed(() => width.value > 1100 ? '550px' : '50%')
const dialogForm = reactive<{
    id?: number,
    nickname?: string,
    username?: string,
    password?: string,
    confirmPassword?: string,
    department?: string,
    role?: RoleType,
}>({})

const createUser = async () => {
    dialogForm.id = undefined
    dialogForm.nickname = ''
    dialogForm.username = ''
    dialogForm.department = ''
    dialogForm.role = undefined
    dialogForm.password = ''
    dialogForm.confirmPassword = ''
    dialogVisible.value = true
    dialogMode.value = 'create'
}

const deleteUser = async (user: User) => {
    if (user.username == 'admin') {
        ElMessage({
            type: 'error',
            message: '不能删除默认管理员账户',
        })
        return
    }
    try {
        await ElMessageBox.confirm('你确定要删除吗', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
        })
    } catch {
        return
    }

    const res = await axios.delete(`/admin/user`, {
        data: {
            userId: user.id,
        }
    })
    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '删除用户失败',
        })
        return
    }
    loadData()
}

const editUser = async (user: User) => {
    dialogForm.id = user.id
    dialogForm.nickname = user.nickname
    dialogForm.username = user.username
    dialogForm.department = user.department
    dialogForm.role = user.role
    dialogForm.password = ''
    dialogForm.confirmPassword = ''
    dialogVisible.value = true
    dialogMode.value = 'edit'
}

const submit = async () => {
    if (dialogMode.value == 'create') {
        submitCreate()
    } else {
        submitEdit()
    }
}
const submitCreate = async () => {
    const userRes = await axios.get(`/admin/user?username=${dialogForm.username}`)
    if (userRes.data['user']) {
        ElMessage({
            type: 'error',
            message: '用户名已存在',
        })
        return
    }

    if (dialogForm.password != dialogForm.confirmPassword) {
        ElMessage({
            type: 'error',
            message: '两次密码不一致',
        })
        return
    }

    if (dialogForm.nickname == '') {
        dialogForm.nickname = dialogForm.username
    }

    const res = await axios.post(`/admin/user`, {
        username: dialogForm.username,
        nickname: dialogForm.nickname,
        password: dialogForm.password,
        department: dialogForm.department,
        role: dialogForm.role,
    })

    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '创建用户失败',
        })
        return
    }

    ElMessage({
        type: 'success',
        message: '创建用户成功',
    })
    dialogVisible.value = false
    loadData()
}

const submitEdit = async () => {
    
    if (dialogForm.password != '' && dialogForm.password != dialogForm.confirmPassword) {
        ElMessage({
            type: 'error',
            message: '两次密码不一致',
        })
        return
    }

    const res = await axios.put(`/admin/user`, {
        userId: dialogForm.id,
        nickname: dialogForm.nickname,
        password: dialogForm.password,
        department: dialogForm.department,
        role: dialogForm.role,
    })

    if (!res.data['ok']) {
        ElMessage({
            type: 'error',
            message: '创建用户失败',
        })
        return
    }

    ElMessage({
        type: 'success',
        message: '修改用户成功',
    })
    dialogVisible.value = false
}

</script>

<template>
    <div class="user-page">
        <el-table
            :data="tableData"
        >
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="昵称" prop="nickname" />
            <el-table-column label="角色" width="80px">
                <template #default="scope">
                    <RoleTag :role="scope.row.role" />
                </template>
            </el-table-column>
            <el-table-column label="部门" prop="department" />
            <el-table-column align="right">
                <template #header>
                    <v-btn color="danger" @click="createUser">新建</v-btn>
                </template>
                <template #default="scope">
                    <v-btn v-if="scope.row.username != 'admin'"  @click="() => deleteUser(scope.row)">删除    </v-btn>
                    <v-btn @click="() => editUser(scope.row)">    编辑</v-btn>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :page-count="pageCount"
            @current-change="loadData"
            />
        
        
        <el-dialog
            :title="dialogMode == 'create' ? '创建新用户' : '编辑用户 ' + dialogForm.nickname"
            v-model="dialogVisible"
            draggable
            align-center
            :width="dialogWidth"
        >
            <el-form :model="dialogForm" label-width="68px">
                <el-form-item label="用户 ID" v-if="dialogMode == 'edit'">
                    <el-input :value="dialogForm.id" readonly />
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="dialogForm.username" placeholder="用于登录账号" :readonly="dialogMode == 'edit'" />
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="dialogForm.nickname" placeholder="留空与用户名一致" />
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="dialogForm.role" style="width: 100%" placeholder="请选择角色">
                        <el-option v-for="r in RoleType" :key="r" :value="r" :label="roleTypeToString(r)">
                            <RoleTag :role="r" />
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门">
                    <el-input v-model="dialogForm.department" />
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="dialogForm.password" type="password" :placeholder="dialogMode == 'edit' ? '留空不修改密码' : '请输入密码'" />
                </el-form-item>
                <el-form-item label="确认密码">
                    <el-input v-model="dialogForm.confirmPassword" type="password" placeholder="两次密码需一致" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="submit">提交</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<style scoped>
.user-page {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin: 20px;
    height: 100%;
}
.el-table {
    height: calc(100% - 100px);
    overflow: auto;
}
.el-pagination {
    height: 100px;
    margin-bottom: 20px;
}


</style>